#include <SDL.h>
#include <stb_declare.h>
#include <cstdio>

void testSdlSwap() {
    SDL_Init(SDL_INIT_EVENTS);
    int width, height, channel;
    unsigned char* image = stbi_load(R"(C:\GraphicsDev\software-renderer\res\cube\container.jpg)", &width, &height, &channel, 4);

    if (image == nullptr) {
        printf("failed to open file\n");
        return;
    }

    SDL_Window* window = SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_Surface* surface = SDL_GetWindowSurface(window);
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);

    bool isQuit = false;
    SDL_Event event[1];

    while (!isQuit) {
        while (SDL_PollEvent(event)) {
            if (event->type == SDL_QUIT) {
                isQuit = true;
            }    
        }
        SDL_SetRenderDrawColor(renderer, 83, 134, 139, 255);
        SDL_RenderClear(renderer);

        for (int i = 0; i < height; ++i) {
            for (int j = 0; j < width; ++j) {
                int index = i * width * 4 + j * 4;
                unsigned char r = image[index];
                unsigned char g = image[index + 1];
                unsigned char b = image[index + 2];
                image[index] = b;
                image[index + 1] = g;
                image[index + 2] = r;
            }
        }

        SDL_UpdateTexture(texture, nullptr, image, sizeof(unsigned char) * 4 * width);

        SDL_RenderCopy(renderer, texture, nullptr, nullptr);
        SDL_RenderPresent(renderer);
        SDL_Delay(500);
    }
    
    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

int main(int, char**) {

    testSdlSwap();

    return 0;
}